define [
	'jquery'
	'helper'
	'lib/jquery.validate.min'
	'template'
	'lib/jquery.couch.js'
], ($, H) ->

	S = {}

	$.validator.addMethod(
		'regex'
		(value, element, regexp) ->
			if regexp.constructor isnt RegExp
				regexp = new RegExp(regexp)
			else if regexp.global
				regexp.lastIndex = 0
			return @optional(element) or regexp.test(value)
		'Format incorrect'
	)
	$.fn.mb_add_donor = (SamCtx) ->
		S = SamCtx
		donor_type = ""
		$this = $(ins = @)
		$tpl = $('.tpl.addDonor > form')
		name = $('input[name="first_name"]').val()

		unless @mb_plugin()
			@mb_plugin 'add_donor'
			$form = $('form', @)
			$.subscribe 'mb.query', (e, arg) ->
				donor_type = arg['search_type']
				$edit = $tpl.clone()
				if donor_type is 'org' then $edit.find(".ind").remove()
				else $edit.find(".org").remove()
				$this.find('.content').empty().append $edit.show()

			$('.content', ins).on 'blur', 'input', ->
				switch $(@).attr('name')
					when "first_name", "last_name", 'org_name'
						if $(@).val().length is 0
							$.publish "mb.msg", {msg: "Name value cannot be empty.", type: "error"}
							$(@).focus()
							return false
					when "postal_code"
						if not $(@).val().isPostal(0)
							$.publish "mb.msg", {msg: "Postal Code is not valid.", type: "warning"}
					when "tel_work", "tel_home", "tel_fax", "tel_contact"
						if not (phone = $(@).val()).isPhone(0)
							# If phone number has 10 digits, then format the phone number ourselves
							if phone.isPhone().length is 10
								$(@).val phone.isPhone(1)
							else
								$.publish "mb.msg", {msg: "Phone Number is in an incorrect format (###) ###-####", type: "warning"}
								return false

			$this.find('.content').on "click", "input:submit", ->
				doc1 = $this.find('.content form').serializeObject()
				if donor_type is "org" then doc1.org = true else doc1.org = false
				H.db().saveDoc(
					doc1 
					success: (data) ->
						$.publish 'mb.donor', {donor_id: data.id}
					error: ->
						$.publish 'mb.error', 'Document is not saved'
				)

		return @

	$.fn.serializeObject = () ->
		doc = {}
		a = @serializeArray()
		$.each a,() -> 
			if doc[@name] isnt undefined
				unless doc[@name].push
					doc[@name] = [doc[@name]]
				doc[@name].push(@value or '')
			else 
				doc[@name] = @value or ''
		return doc
	return @


